package cn.dankal.flyaudio.store;

import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.utils.TextUtils;
import com.example.library.AutoFlowLayout;
import com.example.library.FlowAdapter;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import api.ShopUserServiceFactory;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.ProductEntity;
import cn.dankal.basiclib.pojo.req.AddShopCarReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.HistoryItemAdapter;
import cn.dankal.flyaudio.adapter.StoreProductAdapter;
import cn.dankal.flyaudio.contract.StoreSearchContract;
import cn.dankal.flyaudio.pop.AddShopCarPop;
import cn.dankal.flyaudio.presenter.StoreSearchPresenter;

public class SearchActivity extends BaseActivity implements StoreSearchContract.View, View.OnClickListener {

    private StoreSearchPresenter presenter;

    private TextView salesView;

    private TextView priceView;

    private TextView evaluateView;

    private TextView tvAll;

    private AutoFlowLayout historyItemList;

    private HistoryItemAdapter adapter;

    private View searchHistoryView;

    private View searchResultView;

    private ClearEditText searchView;

    private TextView searchHandleView;

    private RecyclerView storeSearchView;
    private ImageView ivOnback;

    private StoreProductAdapter storeSearchAdapter;

    private boolean isAsc = true;

    private Set<String> history = new HashSet<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_store_search;
    }

    @Override
    protected void initComponents() {
        presenter = new StoreSearchPresenter();
        presenter.attachView(this);
        historyItemList = findViewById(R.id.rv_history_item);
        searchView = findViewById(R.id.et_search);
        ivOnback = findViewById(R.id.iv_onback);
        ivOnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
        searchHistoryView = findViewById(R.id.rl_search_history);
        findViewById(R.id.iv_delete_history).setOnClickListener(this);
        searchResultView = findViewById(R.id.rl_result);
        searchView.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (!TextUtils.isEmpty(keyword)) {
                    history.add(searchView.getText().toString());
                    SharePreferenceManager.setCachedSearchHistory(history);
                }
                presenter.doSearch(searchView.getText().toString(), true);
            }
        });
        searchHandleView = findViewById(R.id.tv_search);
        storeSearchView = findViewById(R.id.rv_classification_store);
        salesView = findViewById(R.id.tv_sales);
        priceView = findViewById(R.id.tv_price);
        tvAll = findViewById(R.id.tv_all);
        evaluateView = findViewById(R.id.tv_evaluate);
        salesView.setOnClickListener(this);
        tvAll.setOnClickListener(this);
        tvAll.setSelected(true);
        evaluateView.setOnClickListener(this);
        priceView.setOnClickListener(this);
        searchView.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    showHistoryLayout();
                } else {
                    showResultLayout();
                }
            }
        });
        searchHandleView.setOnClickListener(this);
        storeSearchAdapter = new StoreProductAdapter();
        storeSearchAdapter.setType("1");
        storeSearchView.setLayoutManager(new GridLayoutManager(this, 2));
        storeSearchView.setAdapter(storeSearchAdapter);
        initHistory();
        showHistoryLayout();
    }

    private void initData() {
//        products.add(new StoreProductModel("科技钛银UPF50+ 五折晴雨两用商务雨伞","¥ 588.00",""));
//        products.add(new StoreProductModel("科沃斯地宝T5MAX扫地机器人智能家用全","¥ 588.00",""));
//        products.add(new StoreProductModel("收纳箱可水洗抽屉式收纳盒家用布","¥ 588.00",""));
//        products.add(new StoreProductModel("复古魅力进阶秘籍，经典金属框时尚太阳镜","¥ 588.00",""));
    }

    private void showHistoryLayout() {
        searchHistoryView.setVisibility(View.VISIBLE);
        searchResultView.setVisibility(View.GONE);
        ivOnback.setVisibility(View.GONE);
        searchHandleView.setVisibility(View.VISIBLE);
    }

    private void showResultLayout() {
        searchHistoryView.setVisibility(View.GONE);
        searchResultView.setVisibility(View.VISIBLE);
        ivOnback.setVisibility(View.VISIBLE);
        searchHandleView.setVisibility(View.GONE);
    }

    private void initHistory() {
        history = SharePreferenceManager.getCachedSearchHistory();
        List<String> historyArr = new ArrayList<>(history);
        historyItemList.setAdapter(new FlowAdapter(historyArr) {
            @Override
            public View getView(int i) {
                View rootView = LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search_history, null, false);
                TextView auto_tv = rootView.findViewById(R.id.tv_key);
                auto_tv.setText(historyArr.get(i));
                return rootView;
            }
        });
        historyItemList.setOnItemClickListener(new AutoFlowLayout.OnItemClickListener() {
            @Override
            public void onItemClick(int i, View view) {
                TextView auto_tv = view.findViewById(R.id.tv_key);
                searchView.setText(auto_tv.getText().toString());
                searchView.setSelection(auto_tv.getText().toString().length());
                String keyword = searchView.getText().toString();
                if (!TextUtils.isEmpty(keyword)) {
                    history.add(searchView.getText().toString());
                    SharePreferenceManager.setCachedSearchHistory(history);
                }
                presenter.doSearch(searchView.getText().toString(), true);
            }
        });

        LiveEventBus.get("StoreProductJoin1", ProductEntity.class)
                .observe(this, new Observer<ProductEntity>() {
                    @Override
                    public void onChanged(ProductEntity s) {
                        //加入购物车
                        searchSku(s.getUuid());

                    }
                });
    }

    public void searchSku(String productUuid) {
        showLoadingDialog();
        ShopUserServiceFactory.shopDetail(productUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<ProductEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<ProductEntity> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        ProductEntity entity = productEntityBaseResponse.getData();
                        if (entity.getItems() == null || entity.getItems().isEmpty()) {
                            addShopCar("-1", 1);
                            return;
                        }
                        if (entity.getItems().size() == 1) {
                            addShopCar(entity.getItems().get(0).getUuid(), 1);
                            return;
                        }
                        new AddShopCarPop(SearchActivity.this).setShop(productEntityBaseResponse.getData()).setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                            @Override
                            public void doAdd(int num, String itemUuid, String desc) {
                                if (android.text.TextUtils.isEmpty(itemUuid)) {
                                    ToastUtils.showShort("没有库存!");
                                    return;
                                }
                                addShopCar(itemUuid, num);
                            }

                            @Override
                            public void doBuy(int num, String itemUuid, String itemDesc) {

                            }
                        }).showPopupWindow(0, 2000);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    public void addShopCar(String productUuid, int count) {
        showLoadingDialog();
        AddShopCarReq req = new AddShopCarReq();
        req.setItemUuid(productUuid);
        req.setItemCount(count + "");
        ShopUserServiceFactory.addShopCar(req)
                .subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
                    @Override
                    public void onNext(BaseResponse<Object> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        ToastUtils.showShort("加入购物车成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    @Override
    public void showProductList(List<ProductEntity> data, boolean isRefresh) {
        storeSearchAdapter.addDatas(data, isRefresh);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_all:
                sortByAll();
                break;
            case R.id.tv_sales:
                sortBySales();
                break;
            case R.id.tv_price:
                sortByPrice();
                break;
            case R.id.tv_evaluate:
                sortByEvaluate();
                break;
            case R.id.tv_search:
                finishActivity();
                break;
            case R.id.iv_delete_history:
                SelectDialog.show(SearchActivity.this, "提示", "是否要删除", "确定", (dialog, which) -> {
                    doDelete();
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
        }
    }

    public void doDelete() {
        SharePreferenceManager.setCachedSearchHistory(new HashSet<>());
        history.clear();
        historyItemList.clearViews();
    }

    public void sortByAll(){
        tvAll.setSelected(true);
        salesView.setSelected(false);
        priceView.setSelected(false);
        evaluateView.setSelected(false);
        presenter.doSearch(searchView.getText().toString(), true, "", true);
    }
    public void sortBySales() {
        salesView.setSelected(true);
        tvAll.setSelected(false);
        priceView.setSelected(false);
        evaluateView.setSelected(false);
        presenter.doSearch(searchView.getText().toString(), true, StoreSearchPresenter.ORDER_BY_SALES, true);
    }

    public void sortByPrice() {
        salesView.setSelected(false);
        priceView.setSelected(true);
        tvAll.setSelected(false);
        evaluateView.setSelected(false);
        presenter.doSearch(searchView.getText().toString(), true, StoreSearchPresenter.ORDER_BY_PRICE, true);
    }

    public void sortByEvaluate() {
        salesView.setSelected(false);
        priceView.setSelected(false);
        tvAll.setSelected(false);
        evaluateView.setSelected(true);
        presenter.doSearch(searchView.getText().toString(), true, StoreSearchPresenter.ORDER_BY_EVALUATE, true);
    }
}
